import { getHouseTypeDetail, labelQueryList, houseAdd, houseUpdate, houseListGet, areAddressGet } from './houseTypeEditServ.js'
import { parse } from 'qs'
import { message } from 'antd'
import moment from 'moment'
import {isEmpty, isArray, cloneDeep, merge} from 'lodash'
import { hashHistory } from 'dva/router'
import { makeAddress } from "utils/util"
import AppBus from 'utils/bus'

// 初始默认状态
const State = {
  btnLoading:false,
  previewVisible:false,
  previewImage:"",
  //操作数据
  detail: {
    medias: [],
    video: []
  },
  //户型图
  localLayoutMediaList:[],
  //样板间图
  localSampleMediaList:[],
  //楼盘标签
  houseTags: [],
  //地址
  allAddress: [],
  //所属楼盘
  houseList: [],
  disabled:false
}

// 声明module
const tmpModule = {
  namespace: 'houseTypeEidt',
  // 默认状态
  state: cloneDeep(State),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        let { actionType, productId} = query
        if('' + tmpModule.pathname === '' + pathname){
          //获取标签
          dispatch({ type: 'getLabelQueryList', payload:  {}});
          //获取户型列表
          dispatch({ type: 'getArea', payload:  {}});
          // 执行业务操作
          dispatch({ type: 'updateStore', payload: {...cloneDeep(State), actionType} });
          if(actionType !='add'){
            //编辑
            dispatch({ type: 'getDetail', payload: {productId} });
          }
        }
      })
    },
  },

  // 方法列表
  effects: {
    // 获取详情
    *getDetail({ payload }, { put, call, select }) {
      try{
        const result = yield call(getHouseTypeDetail, payload)
        let localSampleMediaList = []
        let localLayoutMediaList = []
        //业务类型
        let busiType = {layout: 1, sample: 1, video: 2, house720: 2, vr: 2}
        if(result.success) {
          //console.log(result,"result")
          let detailData = cloneDeep(result.data)
          detailData.medias = []
          //格式化medias
          if (result.data) {
            if (!isEmpty(result.data.medias)) {
              let medias = result.data.medias
              for(var key in medias) {
                if (key == "layout" || key == "sample") {
                  //本地图片
                  let mediaList = []
                  medias[key].forEach((item, idx) => {
                    //提交的图片
                    mediaList.push(item) // ({ uid: idx, status: 'done', url: item })
                  })
                  key == "layout" ? (localLayoutMediaList = mediaList) : (localSampleMediaList = mediaList)
                } else {
                  key == "video" ? detailData.video = medias[key] : detailData[key] = medias[key][0]
                }
              }
            }
            yield put({type: `getHouseArea`, payload: {province: result.data.province, city: result.data.city}})
          }
          yield put({ type: 'updateStore', payload: { detail: detailData, localLayoutMediaList, localSampleMediaList} });
        }
       
      }catch(e){
      
      }
    },
    //新建楼盘
    *saveHouse({payload},{put,call,select}){
      let { detail, localLayoutMediaList, localSampleMediaList, actionType } = yield select(d => d[tmpModule.namespace])
      let params = cloneDeep(detail)
      // 更新视频
      let videoArr = ["video", "vr", "house720"]
      for (var i = 0; i < videoArr.length; i++) {
        let key = videoArr[i]
        if(!isEmpty(params[key])) {
          key == 'video' ? params[key].forEach(item => {
            params.medias.push({busiType: key, fileType: 2, fileUrl: item})
          }) : params.medias.push({busiType: key, fileType: 2, fileUrl: params[key]})
        }
      }
      delete params.video;
      //更新图片
      !isEmpty(localLayoutMediaList) && localLayoutMediaList.forEach(item=>{
        params.medias.push({busiType: 'layout', fileType: 1, fileUrl: item })
      })
      !isEmpty(localSampleMediaList) && localSampleMediaList.forEach(item=>{
        params.medias.push({busiType: 'sample', fileType: 1, fileUrl: item })
      })
      //console.log(params)
      // params.parentProductId = "1049251372579504128"
      try{
        yield put({type: 'updateStore', payload: {loading: true, btnLoading: true,}})
        const service = actionType == 'add' ? houseAdd : houseUpdate
        const result = yield call(service, params)
        yield put({type: 'updateStore', payload: {loading: false, btnLoading: false,}})
        //console.log(result,"result")
        if(result.success){
          yield put({ type: 'updateStore', payload: { disabled:true } });
          message.success('提交成功').then(()=>{
            let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
            //console.log(urlArray,"urlArrayurlArrayurlArrayurlArray")
              AppBus.emit('closeTab', {
                key: urlArray[0],
                cbf: () => {
                  hashHistory.push(urlArray[1])
                }
              })
          });
        }
      }catch(e){
        console.log(e)
      }
    },
    // 获取楼盘标签
    *getLabelQueryList({ payload }, { put, call, select }) {
      try {
        const { rows } = yield call(labelQueryList, {type:2, pageNo:1, pageSize: 99999})
        yield put({ type: 'updateStore', payload: { houseTags: rows } });
      } catch (e) {
        console.log(e)
      }
    },
    // 获取区域地址
    *getArea({ payload }, { put, call, select }) {
      try {
        const { success, data} = yield call(areAddressGet)
        if (success) {
          //todo: 接口格式调整后删除
          let areaList = []
          let arr = [data[0]]
          let attr = [data[data.length-1]]
          data[0] = {
            label:"北京",
            value:"110100",
            children:arr
          }
          data[data.length-1]={
            label:"澳门",
            value:"820000",
            children:attr
          }
          //console.log(data,"data")
          //去掉第三级，
          areaList = makeAddress(data,2,false)
          yield put({type: 'updateStore', payload: {allAddress: areaList }})
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 获取户型项目
    *getHouseArea({ payload }, { put, call, select }) {
      let params = cloneDeep(payload)
      params.pageNo = 1
      params.pageSize = 999999
      try {
        const { success, rows} = yield call(houseListGet, params)
        if (success) {
          yield put({type: 'updateStore', payload: {houseList: rows || [] }})
        }
      } catch (e) {
        console.log(e)
      }
    },
  },

  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return { ...preState, ...action.payload };
    }
  }
}

export default tmpModule
